<template>
  <div class="contentView" :style="`height: ${contentHeight}px`">
    <div class="routeHeader">
      <div class="btn">
        <!-- <el-button
          type="primary"
          @click="submitForm"
          :loading="formLoading"
          v-if="![20, 40].includes(formData.dictStatus)"
          v-hasPermi="['produce:course-machining:save']"
        >
          保存
        </el-button> -->
        <el-button plain @click="goBack"> 关闭 </el-button>
      </div>
    </div>
    <el-scrollbar :max-height="`${contentHeight - 73}px`">
      <div class="title">工单信息</div>
      <ContentWrap v-loading="formLoading">
        <div class="disFlex">
          <div class="cell">
            <span>工单号：</span>
            <span>{{ formData.workTaskNumber }}</span>
          </div>
          <div class="cell">
            <span>产品编号：</span>
            <span>{{ formData.productNumber }}</span>
          </div>
          <div class="cell">
            <span>产品名称：</span>
            <span>{{ formData.productName }}</span>
          </div>
        </div>
        <div class="disFlex bg">
          <div class="cell">
            <span>部件编号：</span>
            <span>{{ formData.partNumber }}</span>
          </div>
          <div class="cell">
            <span>部件名称：</span>
            <span>{{ formData.partName }}</span>
          </div>
          <div class="cell">
            <span>图纸图号：</span>
            <span>{{ formData.drawingNumber }}</span>
          </div>
        </div>
        <div class="disFlex">
          <div class="cell">
            <span>计划数量：</span>
            <span>{{ formData.planQuantity }}</span>
          </div>
          <div class="cell">
            <span>完工数量：</span>
            <span>{{ formData.completeQuantity }}</span>
          </div>
          <div class="cell">
            <span>差异数量：</span>
            <span>{{ formData.differenceQuantity }}</span>
          </div>
        </div>
      </ContentWrap>
      <div class="title mt-10px">生产任务</div>
      <el-table
        border
        :data="[formData]"
        row-key="id"
        default-expand-all
        v-loading="formLoading"
        :header-cell-style="headFirst"
      >
        <el-table-column label="序号" align="center" prop="parentIndex" type="" fixed="left" />
        <el-table-column
          label="工序名称"
          header-align="left"
          align="left"
          prop="dictProcessName"
          min-width="200px"
        >
          <template #default="scope">
            <dict-tag type="craft_process_name" :value="scope.row.dictProcessName" />
          </template>
        </el-table-column>
        <el-table-column
          label="细部工序"
          header-align="left"
          align="left"
          prop="subProcessName"
          min-width="200px"
        />
        <el-table-column
          label="工单号/任务单号"
          header-align="left"
          align="left"
          prop="workTaskNumber"
          min-width="200px"
        />
        <el-table-column
          label="产品编号"
          header-align="left"
          align="left"
          prop="productNumber"
          min-width="200px"
        />
        <el-table-column
          label="产品名称"
          header-align="left"
          align="left"
          prop="productName"
          min-width="200px"
        />
        <el-table-column
          label="产品规格"
          header-align="left"
          align="left"
          prop="productStandard"
          min-width="200px"
        />
        <el-table-column
          label="订单数量"
          header-align="left"
          align="left"
          prop="orderQuantity"
          min-width="200px"
        />
        <el-table-column
          label="编号"
          header-align="left"
          align="left"
          prop="code"
          min-width="200px"
        />
        <el-table-column
          label="部件编号"
          header-align="left"
          align="left"
          prop="partNumber"
          min-width="200px"
        />
        <el-table-column
          label="部件名称"
          header-align="left"
          align="left"
          prop="partName"
          min-width="200px"
        />
        <el-table-column
          label="图纸图号"
          header-align="left"
          align="left"
          prop="drawingNumber"
          min-width="200px"
        >
        <template #default="scope">
            <el-button type="primary" link @click="jumpPdfFile(scope.row.drawingNumber, scope.row.productNumber)">{{
              scope.row.drawingNumber
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="部件规格"
          header-align="left"
          align="left"
          prop="partSpecification"
          min-width="200px"
        />
        <el-table-column
          label="材质"
          header-align="left"
          align="left"
          prop="material"
          min-width="200px"
        />
        <el-table-column
          label="规格"
          header-align="left"
          align="left"
          prop="specification"
          min-width="200px"
        />
        <el-table-column
          label="净尺寸(长)"
          header-align="left"
          align="left"
          prop="netSizeLength"
          min-width="200px"
        />
        <el-table-column
          label="净尺寸(宽)"
          header-align="left"
          align="left"
          prop="netSizeWidth"
          min-width="200px"
        />
        <el-table-column
          label="下料尺寸(长)"
          header-align="left"
          align="left"
          prop="cuttingSizeLength"
          min-width="200px"
        />
        <el-table-column
          label="下料尺寸(宽)"
          header-align="left"
          align="left"
          prop="cuttingSizeWidth"
          min-width="200px"
        />
        <el-table-column
          label="机加工序"
          header-align="left"
          align="left"
          prop="dictMachiningProcess"
          min-width="200px"
        >
          <template #default="scope">
            <dict-tag type="machining_process" :value="scope.row.dictMachiningProcess" />
          </template>
        </el-table-column>
        <el-table-column
          label="计划数量"
          header-align="left"
          align="left"
          prop="planQuantity"
          min-width="200px"
        >
          <template #default="scope">
            <span v-if="scope.row.dictReportWay === 20 && scope.row.isChild"
              >{{ scope.row.planQuantity * 100 }}%</span
            >
            <span v-else>{{ scope.row.planQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="单位"
          header-align="left"
          align="left"
          prop="partUnit"
          min-width="200px"
        />
        <el-table-column
          label="报工数量/报工进度"
          header-align="left"
          align="left"
          prop="reportQuantity"
          min-width="200px"
        >
          <template #default="scope">
            <el-input-number
              controls-position="right"
              :min="0"
              v-model="scope.row.reportQuantity"
              :disabled="[20, 40].includes(scope.row.dictStatus)"
              v-if="
                scope.row.dictReportWay === 10 ||
                (scope.row.dictReportWay === 20 && scope.row.isChild)
              "
            />
            <span v-else>{{ scope.row.reportQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="完工数量"
          header-align="left"
          align="left"
          prop="completeQuantity"
          min-width="200px"
        >
          <template #default="scope">
            <span v-if="scope.row.dictReportWay === 20 && scope.row.isChild"
              >{{ scope.row.completeQuantity * 100 }}%</span
            >
            <span v-else>{{ scope.row.completeQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="差异数量"
          header-align="left"
          align="left"
          prop="differenceQuantity"
          min-width="200px"
        >
          <template #default="scope">
            <span v-if="scope.row.dictReportWay === 20 && scope.row.isChild"
              >{{ scope.row.differenceQuantity * 100 }}%</span
            >
            <span v-else>{{ scope.row.differenceQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="加工单价"
          header-align="right"
          align="right"
          prop="processPrice"
          min-width="200px"
        />
        <el-table-column
          label="生产班组"
          header-align="left"
          align="left"
          prop="productionTeam"
          min-width="200px"
        />
        <el-table-column
          label="设备名称"
          header-align="left"
          align="left"
          prop="deviceName"
          min-width="200px"
        />
        <el-table-column
          label="设备编码"
          header-align="left"
          align="left"
          prop="deviceCode"
          min-width="200px"
        />
        <el-table-column
          label="作业者"
          header-align="left"
          align="left"
          prop="operator"
          min-width="200px"
        />
        <el-table-column
          label="操作"
          header-align="left"
          align="left"
          min-width="370px"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              :loading="formLoading"
              @click="report(scope.row)"
              v-if="
                (scope.row.dictReportWay === 10 ||
                  (scope.row.dictReportWay === 20 && scope.row.isChild)) &&
                ![20, 40].includes(scope.row.dictStatus)
              "
              v-hasPermi="['produce:course-machining:report']"
            >
              报工
            </el-button>
            <template
              v-if="
                scope.row.dictReportWay === 10 || (scope.row.dictReportWay && scope.row.hasChild)
              "
            >
              <el-button
                link
                type="primary"
                @click="showDrawingNumber(scope.row.drawingNumber)"
                v-hasPermi="['produce:course-machining:drawing']"
              >
                查看图纸
              </el-button>
              <el-button
                link
                type="primary"
                @click="showWorkingInstruction(scope.row)"
                v-hasPermi="['produce:course-machining:guide']"
              >
                查看作业指导书
              </el-button>
              <el-button
                link
                size="small"
                type="primary"
                @click="openMaterial(scope.row.productNumber, scope.row.partNumber)"
                v-hasPermi="['produce:course-machining:material']"
              >
                查看物料清单
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div class="title">项目单价</div>
      <div>
        <el-button
          v-if="formData.childListEdit"
          type="primary"
          style="margin-bottom: 10px"
          @click="selectProjectUnitPrice"
          :disabled="[20, 40].includes(formData.dictStatus)"
        >
          选择项目单价
        </el-button>
        <el-table
          border
          :data="formData.childList"
          v-loading="formLoading"
          style="margin-bottom: 10px"
        >
          <el-table-column label="序号" align="center" type="index" fixed="left" />
          <el-table-column
            label="零件名称"
            header-align="left"
            align="left"
            prop="partsName"
            min-width="200px"
          />
          <el-table-column
            label="规格"
            header-align="left"
            align="left"
            prop="specification"
            min-width="200px"
          />
          <el-table-column
            label="加工工序"
            header-align="left"
            align="left"
            prop="processing"
            min-width="200px"
          />
          <el-table-column
            label="单位"
            header-align="left"
            align="left"
            prop="unit"
            min-width="200px"
          />
          <el-table-column
            label="单价（元）"
            header-align="left"
            align="right"
            prop="unitPrice"
            min-width="200px"
          />
          <el-table-column
            label="数量"
            header-align="left"
            align="left"
            prop="quantity"
            min-width="200px"
          >
            <template #default="scope">
              <el-input-number
                controls-position="right"
                :min="0"
                :precision="0.1"
                :disabled="!formData.childListEdit"
                v-model="scope.row.quantity"
                @change="setTotal"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            header-align="left"
            align="left"
            prop="remark"
            min-width="200px"
          />
          <el-table-column
            label="操作"
            header-align="left"
            align="left"
            fixed="right"
            min-width="80px"
          >
            <template #default="scope">
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.$index)"
                v-show="formData.childListEdit && ![20, 40].includes(formData.dictStatus)"
              >
                移除行
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-scrollbar>

    <!-- 项目单价 -->
    <projectUnitPrice ref="projectUnitPriceRef" @selectList="returnProjectUnitPrice" />
    <!-- 完工 -->
    <reportingWorkView ref="reportingWorkRef" @refresh="getData" />
    <!-- 查看作业指导书 -->
    <workingInstruction ref="workingInstructionRef" />
    <!-- 查看图纸 -->
    <drawingNumber ref="drawingNumberRef" />
    <!-- 物料清单 -->
    <material
      v-show="showMaterial"
      class="material"
      ref="materialRef"
      @closeView="showMaterial = false"
    />
  </div>
</template>
<script setup lang="ts">
  import * as CourseMachiningApi from '@/api/produce/processManagement/courseMachining'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import projectUnitPrice from '@/views/configCenter/wageProductionPriceApply/components/projectUnitPrice.vue'
  import reportingWorkView from '../components/reportingWork.vue'
  //查看作业指导书
  import workingInstruction from '../components/workingInstruction.vue'
  //查看图纸
  import drawingNumber from '../components/drawingNumber.vue'
  import material from '../components/material.vue'
  import { jumpPdfFile } from '@/utils/formCreate'
  const workingInstructionRef = ref()
  const showWorkingInstruction = (data) => {
    workingInstructionRef.value.open(data)
  }
  //查看图纸
  const drawingNumberRef = ref()
  const showDrawingNumber = (drawingNumber) => {
    drawingNumberRef.value.open(drawingNumber)
  }
  const message = useMessage() // 消息弹窗
  const materialRef = ref()
  const showMaterial = ref(false)

  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const formData = ref({
    id: undefined,
    workTaskNumber: undefined,
    productNumber: undefined,
    productName: undefined,
    productStandard: undefined,
    orderQuantity: undefined,
    code: undefined,
    partNumber: undefined,
    partName: undefined,
    drawingNumber: undefined,
    partSpecification: undefined,
    material: undefined,
    specification: undefined,
    planEndDate: undefined,
    netSizeLength: undefined,
    netSizeWidth: undefined,
    cuttingSizeLength: undefined,
    cuttingSizeWidth: undefined,
    planQuantity: undefined,
    reportQuantity: undefined,
    completeQuantity: undefined,
    differenceQuantity: undefined,
    workType: undefined,
    productionTeam: undefined,
    deviceName: undefined,
    deviceCode: undefined,
    processPrice: undefined,
    creatorName: undefined,
    updaterName: undefined,
    dictMachiningProcess: undefined,
    planStartDate: undefined,
    operator: undefined,
    operatorJobNumber: undefined,
    dictStatus: undefined,
    children: [],
    childList: [],
    dictReportWay: undefined,
    childListEdit: undefined,
    hasChild: undefined
  })
  const contentHeight = ref(0)

  /** 获取数据 */
  const { query } = useRoute() // 路由的查询
  const getData = async () => {
    formLoading.value = true
    try {
      const res = await CourseMachiningApi.getCourseMachining((query as any).id)
      res.parentIndex = 1
      // 是否显示合并的工序名称
      if (res.children.length) {
        res.hasChild = true
      }
      // 用于报工数量输入框判断
      res.children.map((item) => {
        item.isChild = true
        return item
      })
      // 重新计算加工价格
      if (res.childList.length) {
        let sum = 0
        res.childList.map(item => {
          sum += parseFloat(item['quantity'] || 0) * parseFloat(item['unitPrice'] || 0)
        })
        res.processPrice = sum.toFixed(4)
        if (res.children.length) {
          res.children.forEach(item => {
            item.processPrice = sum.toFixed(4)
          })
        }
      }
      formData.value = res
    } finally {
      formLoading.value = false
    }
  }

  // 打开物料清单
  const openMaterial = (productNumber: string, partNumber: string) => {
    showMaterial.value = true
    materialRef.value!.getData(productNumber, partNumber)
  }

  // 合并工序名称
  const headFirst = ({ rowIndex }) => {
    if (rowIndex === 1) {
      return { display: 'none' }
    }
  }

  /**选择项目单价 */
  const projectUnitPriceRef = ref()
  const selectProjectUnitPrice = () => {
    projectUnitPriceRef.value.open(formData.value.childList, 20, formData.value.dictMachiningProcess)
  }

  // 选中项目单价
  const returnProjectUnitPrice = (list: []) => {
    const data = JSON.parse(JSON.stringify(list))
    formData.value.childList = data
  }

  // 返回
  const tagsViewStore = useTagsViewStore()
  const { currentRoute, push } = useRouter() // 路由
  const goBack = async () => {
    //获取当前路由并删除tagView
    tagsViewStore.delView(currentRoute.value)
    push('/produce/produce/processManagement/courseMachining')
  }

  /** 提交表单 */
  // const submitForm = async () => {
  //   // 提交请求
  //   formLoading.value = true
  //   try {
  //     const data = formData.value as unknown as CourseMachiningApi.CourseMachiningVO
  //     await CourseMachiningApi.updateCourseMachining(data)
  //     goBack()
  //   } finally {
  //     formLoading.value = false
  //   }
  // }

  // 设置加工单价之和
  const setTotal = () => {
    let sum = 0
    formData.value.childList.forEach((item) => {
      sum += parseFloat(item['quantity'] || 0) * parseFloat(item['unitPrice'] || 0)
    })
    formData.value.processPrice = sum.toFixed(4)
    if (formData.value.children.length) {
      formData.value.children.forEach((item) => {
        item.processPrice = sum.toFixed(4)
      })
    }
  }

  // 删除行
  const handleDelete = async (index) => {
    formData.value.childList.splice(index, 1)
  }

  // 报工
  const reportingWorkRef = ref()
  const report = async (row: Object) => {
    if (!formData.value.processPrice) {
      message.notifyError('请选择项目单价')
      return
    }
    if (row['dictReportWay'] === 10) {
      if (parseFloat(row['reportQuantity']) > parseFloat(row['differenceQuantity'])) {
        message.notifyError('报工数量不能大于差异数量')
        return
      }
      if (!row['reportQuantity']) {
        message.notifyError('请输入报工数量')
        return
      }
    } else {
      if (parseFloat(row['reportQuantity']) / 100 > parseFloat(row['differenceQuantity'])) {
        message.notifyError('报工进度不能大于差异进度')
        return
      }
      if (!row['reportQuantity']) {
        message.notifyError('请输入报工进度')
        return
      }
    }
    reportingWorkRef.value.open(row, 'produce/course-machining/workTime', formData.value.planQuantity, formData.value.childList)
  }

  onMounted(() => {
    contentHeight.value = document.body.clientHeight - 126
    getData()
  })
</script>
<style lang="scss" scoped>
  .contentView {
    position: relative;

    :deep(.el-scrollbar) {
      height: auto;
    }

    .material {
      width: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 99;
    }

    .mt-10px {
      margin-top: 10px;
    }

    .title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .disFlex {
      display: flex;
    }

    .cell {
      width: 33%;
      height: 60px;
      line-height: 60px;
      padding-left: 10px;
      box-sizing: border-box;
    }

    .bg {
      background-color: #f0f1f5;
    }
  }
</style>
